﻿function FillReturnMsg(o, t, msg) {
    var tip = $("span.formcolumn-item-tipstxt", $(o).parent());
    if ($("span.formcolumn-item-errtipstxt", $(o).parent()).length > 0) {
        tip = $("span.formcolumn-item-errtipstxt", $(o).parent());
    }
    tip.html(msg);
    if (t == 1) {
        $(o).removeClass("needFill");
        tip.css("color", "green");
    }
    else if (t == 0) {
        $(o).addClass("needFill");
        tip.css("color", "red");
    }
    else if (t == 2) {
        $(o).removeClass("needFill");
        tip.css("color", "#999999");
    }
}
function InitFormVerify(cfg) {
    if (typeof (InitExtCountry) == "function") {
        InitExtCountry();
    }
    $("input[exrequired='true'],textarea[exrequired='true']", cfg.el).after(" <span style=\"color:red\">*</span>");

    $("input[exrequired='true'],textarea[exrequired='true']", cfg.el).each(function () {
        if ($(this).attr("onblur") == undefined) {
            $(this).on("blur", function () {
                var v = $(this).val();
                if (v != "") {
                    FillReturnMsg(this, 1, "&nbsp;");
                }
                else {
                    if ($(this).attr("title")) {
                        FillReturnMsg(this, 0, GetLangTxt(rclng.itemrequired, [{ title: "title", text: $(this).attr("title") }]));
                    }
                    else {
                        FillReturnMsg(this, 0, "");
                    }
                }
            });
        }
    });
}
function InitFormVerify_V2(cfg) {
    if (typeof (InitExtCountry) == "function") {
        InitExtCountry();
    }
    // $("input[exrequired='true'],textarea[exrequired='true']", cfg.el).after(" <span style=\"color:red\">*</span>");

    $("input[exrequired='true'],textarea[exrequired='true']", cfg.el).each(function () {
        if ($(this).attr("onblur") == undefined) {
            $(this).on("blur", function () {

                $(".help-block", $(this).parents(".form-group")).remove();
                var v = $(this).val();
                if (v != "") {

                    $(this).parents(".form-group").removeClass("has-error");
                }
                else {
                    $(this).parents(".form-group").addClass("has-error");
                    if ($(this).attr("title") && $(this).attr("show-help") == "true") {
                        $(this).parents(".form-group").append('<span class="help-block">' + GetLangTxt(rclng.itemrequired, [{ title: "title", text: $(this).attr("title") }]) + '</span>');

                    }
                }
            });
        }
    });
}
function AjaxReturn(ret, callback) {
    var rc = ret.value;
    if (rc) {
        callback();
    }
    else {
        alert(ret.error.Message);
    }
}
function OpenDialog(cfg) {
    if ($.fn.dialog != undefined) {
        $(cfg.el).dialog({
            title: cfg.title,
            autoOpen: true,
            modal: true,
            width: cfg.width,
            resizable: false,
            close: function () {
                $("body").css("overflow", "auto");
                NowOpenDialogEl = '';
            },
            open: function () {
                $("body").css("overflow", "hidden");
                if (cfg.opencallback != undefined) {
                    cfg.opencallback();
                }
            }

        });
    }
    else {
        try {
            var modalel = cfg.el + "_modal";
            var modalelstr = modalel.replace("#", "").replace(".", "");
            if ($(modalel).length == 0) {
                var html = '<div class="modal fade" id="' + modalelstr + '" tabindex="-1" role="dialog" aria-labelledby="' + modalelstr+'ModalLabel">\
                          <div class="modal-dialog" role="document">\
                            <div class="modal-content">\
                              <div class="modal-header">\
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>\
                                <h4 class="modal-title" id="' + modalelstr + 'ModalLabel">' + cfg.title + '</h4>\
                              </div>\
                              <div class="modal-body">\
                              </div>\
                            </div>\
                          </div>\
                        </div>';
                $("body").append(html);
                $(cfg.el).show();
                $(".modal-body", modalel).append($(cfg.el));
                $(modalel).modal({
                    backdrop: false,
                    keyboard: false,
                    show: true
                });
                $(modalel).on('shown.bs.modal', function (e) {
                    if (cfg.opencallback != undefined) {
                        cfg.opencallback();
                    }
                });
            }
            else {
                $(modalel).modal("show");
            }
        }
        catch(e){ }
    }
}
function Alert(msg, title, width) {
    if (title == undefined) {
        title = "" + rclng.sysalert;
    }
    if (width == undefined) {
        width = 400;
    }
    if ($("#AlertDialog").length == 0) {
        $("body").append('<div id="AlertDialog"><div id="AlertMsgBox" style="padding: 20px;"></div></div> ');
    }
    OpenDialog({
        el: "#AlertDialog",
        width: width,
        title: title,
        buttons: [
            {
                text: "" + rclng.sysok,
                icons: {
                    primary: "ui-icon-heart"
                },
                click: function () {
                    $(this).dialog("close");
                }
            }
        ],
        opencallback: function () {
            $("#AlertMsgBox").html(msg);
        }
    });
}
function CloseDialog(el) {
    if ($.fn.dialog != undefined) {
        $(el).dialog("close");
    }
    else {
        try {
            var modalel = el + "_modal";
            $(modalel).modal("hide");
        }
        catch (e) {
        }
    }
}
function AutoCenterDialog(el) {
    if ($.fn.dialog != undefined) {
        $(el).dialog("option", "position", "center");
    }
}
function initCloseBtn(o) {
    if (o != undefined) {
        $("input[closebtn='true']", o).bind("click", function () {
            var el = $(this).attr("reel");
            CloseDialog("#" + el);
        })
    }
    else {
        $("input[closebtn='true']").bind("click", function () {
            var el = $(this).attr("reel");
            CloseDialog("#" + el);
        })
    }
}
function GetExtAttrValues(cfg) {
    var extv = {};
    $("input[dataref='true'],textarea[dataref='true'],select[dataref='true'],span[addresstype],span[countrytype]", $(cfg.el)).each(function () {
        if (extv[$(this).attr("classname")] == undefined) {
            extv[$(this).attr("classname")] = {};
        }
        if ($(this).hasClass("address_extipt")) {
            var vxv = "";
            if ($(this).attr("areacode") != "") {
                vxv = $(this).attr("areacode") + "|" + $(this).attr("areatitle");
            }
            extv[$(this).attr("classname")][$(this).attr("relkey")] = vxv;
        }
        else if ($(this).hasClass("country_extipt")) {
            var vxv = "";
            if ($(this).attr("countrycode") != "") {
                vxv = $(this).attr("countrytitle") + "|" + $(this).attr("countrycode");
            }
            extv[$(this).attr("classname")][$(this).attr("relkey")] = vxv;
        }
        else {
            extv[$(this).attr("classname")][$(this).attr("relkey")] = $(this).val();
        }
    });
    var r = {};
    r.str = JSON2.stringify(extv);
    r.json = extv;
    return r;
}
function ClearFormData(cfg, callback) {
    $("input[dataref='true'][type!='checkbox'],textarea[dataref='true'],input[data-ref][type!='checkbox'],textarea[data-ref]", $(cfg.el)).val("");
    if (callback != undefined) {
        callback();
    }
}
function VerifyFormData(cfg, callback) {
    var success = true;
    var postdata = {};
    $("input[dataref='true'],textarea[dataref='true'],select[dataref='true'],input[data-ref],textarea[data-ref],span[addresstype],span[countrytype]", $(cfg.el)).each(function () {
        var v = "";
        if ($(this).attr("addresstype") != undefined || $(this).attr("countrytype") != undefined) {
            v = $(this).attr("areacode");
        }
        else {
            v = $(this).val();
        }

        if ($(this).attr("exrequired") == "true" && v == "") {
            alert(GetLangTxt(rclng.itemrequired, [{ title: "title", text: $(this).attr("title") }]));
            success = false;
            $(this).focus();
            return false;
        }
        if ($(this).attr("data-ref") != undefined) {
            if ($(this).attr("type") != undefined) {
                if ($(this).attr("type") == "checkbox") {
                    if ($(this).is(":checked")) {
                        postdata[$(this).attr("data-ref")] = v;
                    }
                    else {
                        postdata[$(this).attr("data-ref")] = "";
                    }
                }
                else {
                    postdata[$(this).attr("data-ref")] = v;
                }
            }
            else {
                postdata[$(this).attr("data-ref")] = v;
            }
        }
    });
    if (success) {
        var extdata = GetExtAttrValues(cfg);
        callback(postdata, extdata.str, extdata.json);
    }
}
function JsonToDict(data) {
    var dict = new Ajax.Web.Dictionary("Dictionary<string,string>");
    for (var jd in data) {
        dict.add(jd, data[jd]);
    }
    return dict;
}
function InitUserLoginStatus(cfg) {
    $.get("/index.aspx?a=checkuserlogin&mfrsh=" + Math.random(), {}, function (data) {
        if (cfg.callback == undefined) {
            if (data.result == "1") {
                $(cfg.el).html(rclng.hello + '！<b>' + data.username + '</b> <a href="' + data.usercenter + '">' + rclng.membercenter + '</a> <a href="' + data.loginouturl + '">' + rclng.loginout + '</a> ');
            }
            else if (data.result == "-1") {
                $(cfg.el).html('<a href="' + data.loginurl + '">' + rclng.login + '</a> <a href="' + data.regurl + '">' + rclng.register + '</a> ');
            }
            if (cfg.ondone != undefined) {
                cfg.ondone(data);
            }
        }
        else {
            cfg.callback(data);
        }
    }, "json");
}
function ViewVerifyImage(cfg) {
    $(cfg.el).html('<img src="/index.aspx?a=verifycode&verifytype=' + cfg.verifytype + '" verifytype="' + cfg.verifytype + '" vref="' + cfg.ref_el + '" onclick="ReFreashVerifyImg(this);" />');

}
function ReFreashVerifyImg(o) {
    var verifytype = $(o).attr("verifytype");
    var veid = $(o).attr("vref");
    $(o).attr("src", "/index.aspx?a=verifycode&verifytype=" + verifytype + "&r=" + Math.random());
    $(veid).val("");
}
function VerifyCodeCheck(o) {
    var v = $(o).val();
    Web960.Web.index.verifyRegCode(v, "userlogin", function (res) {
        AjaxReturn(res, function () {
            var rv = res.value;
            if (rv.Status == "1") {

            }
            else {
                // rv.ClientMsg
            }
        });

    });
}
function InitDataMapping() {
    $.get("/index.aspx?a=getuserinfo", {}, function (data) {
        if (data.IntResult == 1) {
            //logined;

            var comment = eval("(" + data.ObjResult.comment + ");");

            $("input[data-mapping],textarea[data-mapping],select[data-mapping]").each(function () {
                var mapping = $.trim($(this).attr("data-mapping"));
                if (mapping != "") {
                    try {
                        var v = eval("(comment." + mapping + ");");

                        $(this).val(v);
                    }
                    catch (e) { }
                }
            })
        }
    }, "json");
}
function GetGuestExtSettings(callback) {
    $.get("/index.aspx?a=g&getmethod=getsettings", {}, function (data) {
        if (data.IntResult == 1) {
            var json = eval('(' + data.StrResult + ')');
            callback(json);
        }
    }, "json");
}
function GetExtForms(formid, callback) {
    $.get("/index.aspx?a=g&getmethod=getextforms&formid=" + formid, {}, function (data) {
        if (data.IntResult == 1) {
            callback(data.StrResult);
        }
    }, "json");
}
function Guid(callback) {
    $.get("/index.aspx?a=guid&rnd=" + Math.random(1), {}, function (data) {
        callback(data.guid);
    }, "json");
}
function GoToPage(o) {
    var v = $.trim($(o).val());
    var patrn = /^[1-9]*[1-9][0-9]*$/;
    if (patrn.exec(v)) {
        var page = parseInt(v);
        var url = $(o).attr("pageurl");
        var pagecount = parseInt($(o).attr("pagecount"));
        if (page <= 1) {
            url = url.replace("-{0}", "").replace("_{0}", "");
        }
        else if (page > pagecount) {
            page = pagecount;
            url = url.replace("{0}", page);
        }
        else {
            url = url.replace("{0}", page);
        }
        location.href = url;
    }

}
function jumppropage(o) {
    var v = $.trim($(o).val());

    var url = $("#wpagenavgotuipt").attr("pageurl");
    var pagecount = parseInt($(o).attr("pagecount"));
    url = url.replace("-{0}", "").replace("_{0}", "").replace("page={0}", "page=").replace("&psize", "&apsizeq").replace("?psize", "?apsizeq");
    if (url.indexOf("?") == -1) {
        location.href = url + "?psize=" + v;
    } else {
        location.href = url + "&psize=" + v;
    }
}
function GetSimpMoneyUnit(m) {
    switch (m) {
        case "CNY":
        case "元":
            return "¥";
        case "USD":
            return "$";
        case "HKD":
            return "HK$";

        case "EUR":
            return "€";
    }
}
function InitBrowseHistoryCookie(cookiename, cookievalue, savetime) {

    var str = cookiename + "=" + escape(cookievalue);
    var date = new Date();
    var ms = savetime * 60 * 1000;
    date.setTime(date.getTime() + ms);

    str += ";expires=" + date.toGMTString();

    document.cookie = str;
}
var nowExtUploadRefId = "";
var BFCallBack = null;
function ExtUpload(t, elid, callback) {
    BFCallBack = callback;
    var dialoghtml = '<div id="ExtUploadDialog" style="display: none;">'
        + ' <div style="padding: 10px;">'
        + '     <div id="uploadnoticediv"></div><iframe name="ifrmExtUpFile" id="ifrmExtUpFile" style="display:none;"></iframe>'
        + '    <form enctype="multipart/form-data" id="ExtUploadForm" method="post" target="ifrmExtUpFile">'
        + '        <input type="file" id="extupfileipt" name="extupfileipt" /> <input type="button" value="' + rclng.uploadfile + '" class="buttonok" onclick="$(\'#ExtUploadForm\').submit();" />'
        + '     </form>'
        + '    </div>'
        + '</div>';
    if ($("#ExtUploadDialog").length == 0) {
        $("body").append(dialoghtml);
        ExtUpload(t, elid);
    }
    else {
        $("#uploadnoticediv").html("");
        nowExtUploadRefId = elid;
        if (t == 1) {
            title = rclng.uploadimage;
            $("#ExtUploadForm").attr("action", "/admin/filehandler.aspx?t=100&dir=image&id=0&n=0&cb=ExtUploadCallBack");
        } else if (t == 2) {
            title = rclng.uploadfile;
            $("#ExtUploadForm").attr("action", "/admin/filehandler.aspx?t=110&dir=file&id=0&n=0&cb=ExtUploadCallBack");
        }
        OpenDialog({ el: "#ExtUploadDialog", width: 410, title: title });
    }
}
function ExtUploadCallBack(res) {
    if (res.error == "1") {
        alert(res.message);
    }
    else {
        var fileName = res.filename;
        $("input[id$='" + nowExtUploadRefId + "'").val(fileName);
        if (BFCallBack) {
            BFCallBack(fileName);
        }
        CloseDialog("#ExtUploadDialog");
    }
}
function GetShopChatCountForNowUser(cfg) {
    $.get("/index.aspx?a=ajax&plu=goodsmanage&ajaxmethod=shopcharcount&rnd=" + Math.random(), {}, function (data) {
        if (cfg.callback == undefined) {

        }
        else {
            cfg.callback(data);
        }
    }, "json");
}
///获取待确认订单的数量
function GetCountorderwating() {
    $.get("/index.aspx?a=getorderwatingcount", {}, function (data) {
        var res = data;
        if (data.result == 1) {
            var ct = data.count;
            if ($(".ordermanage_orderwating").length > 0) {
                var sphtm = "<span class='licount'>" + ct + "</span>";
                $(".ordermanage_orderwating a").append(sphtm);
            }
        }


    }, "json");
}

function RequestLoginAuthInfo(callback) {


    var html = '<div id="loginauthinfobox">\
            <div style="padding:10px;"><input type="password" style="height:30px; width:100%;"  id="loginauthinfotext" placeholder="' + rclng.loginpassword + '" /></div>\
<div style="border-top:1px solid #dddddd;text-align:right; padding:10px 10px 0px 0px;"><input id="loginauthinfobutton" class="loginauthinfobutton" type="button" value="' + rclng.btnok + '" /></div>\
            </div>';
    html = '<div class="modal fade" id="loginauthinfobox" tabindex="-1" role="dialog" aria-labelledby="loginauthinfoboxModalLabel">\
  <div class="modal-dialog" role="document">\
    <div class="modal-content">\
      <div class="modal-header">\
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>\
        <h4 class="modal-title" id="loginauthinfoboxModalLabel">' + rclng.loginpassword + '</h4>\
      </div>\
      <div class="modal-body">\
        <div>\
          <div class="form-group">\
            <input type="password" class="form-control" id="loginauthinfotext"  placeholder="' + rclng.loginpassword + '">\
          </div>\
        </div>\
      </div>\
      <div class="modal-footer">\
        <button type="button" class="btn btn-primary" id="loginauthinfobutton">' + rclng.btnok + '</button>\
      </div>\
    </div>\
  </div>\
</div>';
    if ($("#loginauthinfobox").length == 0) {
        $("body").append(html);
    }
    $('#loginauthinfobox').modal('show');
    $("#loginauthinfotext").on("keypress", function () {
        if (event.keyCode == 13) {
            var v = $("#loginauthinfotext").val();
            if (v != "") {
                $("#loginauthinfotext").val("");
                $('#loginauthinfobox').modal('hide')
                callback(v);
            }
        }
    });

    $("#loginauthinfobutton").unbind("click").click(function () {
        var v = $("#loginauthinfotext").val();
        if (v != "") {
            $("#loginauthinfotext").val("");
            $('#loginauthinfobox').modal('hide')
            callback(v);
        }
    });
    //OpenDialog({
    //    el: "#loginauthinfobox", width: 300, title: rclng.loginpassword, opencallback: function () {
    //        $("#loginauthinfobutton").unbind("click").click(function () {
    //            var v = $("#loginauthinfotext").val();
    //            if (v != "") {
    //                $("#loginauthinfotext").val("");
    //                CloseDialog("#loginauthinfobox");
    //                callback(v);
    //            }
    //        });
    //    }
    //});
}
function GetFields(target) {
    ///	<summary>
    ///	根据属性field 从指定的页面区域获取内容 , 返回实体 :{NavId="...",NavName=".."}
    /// 多实体格式 {entity1:{field1:123,field2:234},entity2:{fiel:123,fiel2:123},otherField:"abc"}
    /// 对选支持:格式[]
    ///	</summary>
    ///	<param name="target" type="DOM">
    /// 页面区域
    ///	</param>
    ///	<return>
    ///	实体内容
    ///	</return>

    var entity = {};
    if (target == undefined)
        target = this._container;

    var allfileds = $("[field]", target);
    allfileds.each(function (i) {
        var tagName = this.tagName;
        var element = $(this);
        var key = element.attr("field");

        var tokens = key.toString().split('.');


        var tokevalue = function (v) {
            ///	<summary>
            ///	实体赋值
            ///	</summary>
            if (tokens != undefined && tokens.length && tokens.length > 1) {
                if (entity[tokens[0]] == undefined)
                    entity[tokens[0]] = {};
                entity[tokens[0]][tokens[1]] = v;
            }
            else {
                entity[key] = v;
            }
        };
        //根据元素不同做不同处理
        if (element.attr("type") == "radio") {
            $("[name='" + element.attr("name") + "']", target).each(function () {
                var r = $(this);
                if (r.prop("checked")) {
                    tokevalue($.trim(r.val()));
                }
            });
        } else if (element.attr("type") == "checkbox") {
            if (element.attr("name") == undefined) {
                if (element.is(":checked")) {
                    tokevalue($.trim(element.val()));
                }
            }
            else {
                var last = [];
                $("[name='" + element.attr("name") + "']", target).each(function () {
                    var r = $(this);
                    if (r.attr("checked")) {
                        last.push($.trim(r.val()));
                    }
                });
                tokevalue(last);
            }
        } else if (tagName == "DIV") {
            tokevalue($(this).html());
        }
        else {
            //tokevalue($.trim($(this).val()));
            tokevalue($(this).val());
        }
    });

    return entity;
}

function SetFields(data, target) {
    ///	<summary>
    ///	初始化页面
    /// 多实体格式 {entity1:{field1:123,field2:234},entity2:{fiel:123,fiel2:123},otherField:"abc"}
    /// HTML:<input field="entity1.field1" /><input field="entity2.fiel" />...
    /// 支持多选,多选返回[]
    ///	</summary>
    ///	<param name="entity" type="Object">
    /// 实体内容
    ///	</param>
    ///	<param name="target" type="DOM">
    /// 页面区域
    ///	</param>
    var entity = data;
    if (entity == null) {
        return;
    }
    if (entity == undefined)
        return;
    if (target == undefined)
        target = this._container;

    var allfileds = $("[field]", target);
    var a = "";

    allfileds.each(function (i) {
        var element = $(this);
        var key = element.attr("field");

        var tokens = key.toString().split('.');
        var val;
        if (tokens != undefined && tokens.length && tokens.length > 1) {
            var ent = entity[tokens[0]];
            if (ent != undefined)
                val = ent[tokens[1]];
        }
        else {
            val = entity[key];
        }
        if (val != undefined) {
            if (val == null) {
                val = "";
            }
            if (element.attr("type") == "radio") {
                $("[name='" + element.attr("name") + "']", target).each(function () {
                    if ($(this).val() == val)
                        $(this).attr("checked", "checked");
                    else
                        $(this).removeAttr("checked");
                });
            } else if (element.attr("type") == "checkbox") {
                $.each(val, function (index) {
                    var thatelemetn = $("[name='" + element.attr("name") + "'][value='" + val[index] + "']", target);
                    thatelemetn.attr("checked", "checked");
                });
            }
            else {
                if (this.nodeName == "TD" || this.nodeName == "DIV") {
                    element.html(val);
                } else {
                    element.val(val);
                }
            }
        }
    });
}

function JSONtoURLPath(json) {
    var r = "";
    for (var key in json) {
        r += "&" + key + "=" + escape(json[key]);
    }
    r = r.length > 0 ? r.substr(1) : r;
    return r;
}